import {messages, queryCurrencyPrecision } from "share/common";
import React  from 'react'
import { connect } from 'react-redux'
import { Button, Menu, Dropdown, Icon, Popconfirm, Popover, message, Tooltip, Modal, Alert, Row, Col } from 'antd'
import 'styles/my-account/my-account.scss'
import SlideFrame from "components/slide-frame";
import NewExpense from 'containers/my-account/new-expense'
import expenseService from 'containers/my-account/expense.service'
import baseService from 'share/base.service'
import errorMessage from "share/errorMessage";
import Selector from 'components/selector'
import Condition from 'components/condition'
import config from "config";
import SearchArea from "components/search-area";
import ResizeTable from 'components/resize-table'
const { If, Else } = Condition;

class MyAccount extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      data: [],
      columns:[
        {title: messages('common.sequence')/*序号*/, dataIndex: 'index', width: 48},
        {title: messages('common.expense.type')/*费用类型*/, dataIndex: 'expenseTypeName', render: expenseTypeName => <Popover content={expenseTypeName}>{expenseTypeName}</Popover>},
        {title: messages('common.date')/*日期*/, dataIndex: 'createdDate', render: createdDate => new Date(createdDate).format('yyyy-MM-dd'), width: 120},
        {title: messages('common.accountIncident')/*事由说明*/, dataIndex: 'comment', render: comment => <Popover content={comment}>{comment || '-'}</Popover>},
        {title: messages("common.attachments")/*附件*/, dataIndex: 'attachments', width: 58, render: attachments => attachments.length},
        {title: messages("common.currency")/*币种*/, dataIndex: 'invoiceCurrencyCode', width: 58},
        {title: messages("common.amount")/*金额*/, dataIndex: 'amount', align: 'right', render: (value,item)=>this.filterMoney(value,queryCurrencyPrecision(item.invoiceCurrencyCode)), width: '8%'},
        {title: messages("common.base.currency.amount")/*本位币金额*/, align: 'right',dataIndex: 'baseAmount', render: (value)=>this.filterMoney(value,queryCurrencyPrecision('')), width: '8%'},
        {title: messages('my-account.key170')/*摘要信息*/, dataIndex: 'summaryInfo', render: value => (
            value ? <Popover content={value} placement="topLeft" overlayStyle={{maxWidth: 350}}>{value}</Popover> : '-'
          )},
        {title: messages('my-account.key171')/*费用归属人*/, dataIndex: 'owner', width: '10%', render: (value, record) => {
            let showValue = value && value.fullName;
            if (showValue && record.reimbursementUserOID && record.ownerOID && record.reimbursementUserOID !== record.ownerOID)
              showValue += `（${messages('my-account.key232')/*已转交*/}：${record.reimbursementUserName}）`;
            return showValue ? <Popover content={showValue}>{showValue}</Popover> : '-'
          }},
        {title: messages("common.operation")/*操作*/, dataIndex: 'operate', width: '10%',render: this.renderOperate}
      ],
      pagination: {
        total: 0,
      },
      page: 0,
      pageSize: 10,
      nowExpense: null,
      showExpenseFlag: false,
      isCopy: false,
      expenseSource: '',
      businessCardEnabled: false,
      invoiceEnabled: false,
      selectedRowKeys: [],
      modalVisible: false,
      transferLoading: false,
      reimbursementUserOID: '', //转交人OID
      reimbursementUserId: '', //转交人id
      reimbursementUserName: '', //转交人name
      receiptOperateScene: 1,//发票操作场景：1.发票创建费用；2.费用新增发票；3.费用编辑发票
      debounceSlideFrame: false, //侧滑框防抖，解决快速关闭侧滑框的情况
      searchForm: [{
        type: 'multiple',
        id: 'expenseTypeIds',
        label: messages('common.expense.type')/*费用类型*/,
        options: [],
        getUrl: `${config.baseUrl}/api/expense/type/company/all/icons`,
        method: 'get',
        labelKey: 'name',
        valueKey: 'id',
        searchKey: 'name'
      }]
    };
  }

  enableDeleteHandle = (event, record) => {
    event.stopPropagation();
    event.preventDefault();
    const { user } = this.props;
    if (record.paymentType === 1002 && record.readonly) {
      message.error(messages('my-account.key182')/*公司支付费用，不可删除*/);
      return
    }
    if (record.createdBy !== user.userOID && record.ownerOID !== user.userOID) {
      message.error(messages('my-account.key233')/*他人转交费用，不可删除！*/)
    }
  };

  deleteExpense = (record, isConfirm) => {
    const { expenseTypeIds } = this.state;
    this.setState({ loading: true });
    expenseService.deleteExpense(record.invoiceOID, isConfirm).then(res => {
      if (res.data.code === '0020') {
        Modal.confirm({
          title: res.data.message,
          onOk: () => this.deleteExpense(record, true),
          onCancel: () => this.setState({ loading: false })
        })
      } else {
        message.success(messages('common.operate.success'));
        if(this.state.data.length === 1){
          this.setState({ page: 0 }, () => this.getList({ expenseTypeIds }))
        } else {
          this.getList({ expenseTypeIds });
        }
      }
    }).catch(e => {
      errorMessage(e.response);
      this.setState({ loading: false })
    })
  };

  copyInvoice = (record,event) => {
    event.preventDefault();
    event.stopPropagation();
    if (!record.ableToCreatedManually) {
      message.error(messages('my-account.key183')/*不可复制*/);
      return !1;
    }
    expenseService.validateCopyInvoice({invoiceOID: record.invoiceOID}).then(() => {
      this.setState({showExpenseFlag: true, nowExpense: record, isCopy: true})
    }).catch((e) => {
      errorMessage(e.response);
    })
  };

  print  = (record,event) => {
    event.preventDefault();
    event.stopPropagation();
    event.cancelBubble = true;
    // 微信打印
    expenseService.printInvoice(record.digitalInvoice.id).then((res) => {
      window.open(res.data.rows.fileURL, "_blank");
    }).catch((e) => {
      message.error(messages('common.operate.filed'));//操作失败
    });
  };

  renderOperate = (text, record) => {
    const { user } = this.props;
    let labels = record.invoiceLabels || [];
    let printButton = true;
    labels.map(items => {
      items.type === 'INVOICE_FREE' && (printButton = false);
    });
    let deleteContent;
    if(record.digitalInvoice && record.digitalInvoice.cardsignType === 'ALICARDSIGN'){
      deleteContent = messages('my-account.key62'/*删除后电子票将回到支付宝电子卡包*/)
    }
    if(record.digitalInvoice &&
      (record.digitalInvoice.cardsignType === 'JSCARDSIGN' || record.digitalInvoice.cardsignType === 'APPCARDSIGN')){
      deleteContent = messages('my-account.key63'/*删除后电子票将回到微信电子卡包*/)
    }
    let deleteContents = <span>{messages("common.confirm.delete")/*确定要删除吗？*/}<br/>{deleteContent}</span>;
    //费用是否能删除
    let isNotDelete = (
      (record.paymentType === 1002 && record.readonly) || //公司支付费用
      (record.createdBy !== user.userOID && record.ownerOID !== user.userOID) //当前登录人既不是费用创建人也不是费用归属人
    );

    return (
      <span>
        <span>
          <a className={record.ableToCreatedManually ? '' : 'button-disabled'}
             onClick={e => this.copyInvoice(record, e)}>{messages('common.copy')/*复制*/}</a>
        </span>
        <span className="ant-divider"/>
        <Condition>
          <If value={isNotDelete}>
            <a className="button-disabled" onClick={e => this.enableDeleteHandle(e, record)}>
              {messages("common.delete")}
            </a>
          </If>
          <Else>
             <Popconfirm title={deleteContents} onConfirm={() => this.deleteExpense(record)}>
               <a onClick={e => e.stopPropagation()}>{messages("common.delete")}</a>
             </Popconfirm>
          </Else>
        </Condition>
        {/* 费用打印 支付宝处理*/}
        <If value={false && record.digitalInvoice && (
          (record.digitalInvoice.cardsignType === 'ALICARDSIGN' && record.digitalInvoice.pdfUrl) ||
          record.digitalInvoice.cardsignType === 'APPCARDSIGN' ||
          record.digitalInvoice.cardsignType === 'JSCARDSIGN'
        ) && printButton}>
          <span>
            <span className="ant-divider" />
            <a onClick={e => this.print(record, e)}>{messages('common.print')/*打印*/}</a>
          </span>
        </If>
      </span>)
  };

  componentWillMount(){
    this.getList();
    Promise.all([
      /**
       * baseService.getBusinessCardConsumptionList这个接口的page size传0，0时
       * 意味着不是真的想获取公务卡数据，只是想判断这个用户是否有公务卡消费记录
       * 因为获取公务卡消费记录的时候会剔除掉已关联的公务卡消费记录
       * 如果用户的所有公务卡消费记录都被关联了，就查不出来数据了，所以增加了这一条传参约定
       */
      baseService.getBusinessCardConsumptionList('CMBC', false, this.props.user.userOID, 0, 0),
      expenseService.getBusinessCardStatus()
    ]).then(res => {
      this.setState({ businessCardEnabled: res[0].data.success && res[0].data.rows.length > 0 && res[1].data.rows })
    });
    expenseService.getTitleList(this.props.user.userOID).then(res => {
      this.setState({ invoiceEnabled: res.data.showCheckInvoiceFlag })
    })
  }

  getList = (ids = { expenseTypeIds: [] }) => {
    let { page, pageSize } = this.state;
    const { expenseTypeIds } = ids;
    this.setState({ loading: true });
    expenseService.getExpenseList(page, pageSize, expenseTypeIds).then(res => {
      if (res.data && res.data.rows) {
        res.data.rows.map((item, index) => {
          item.index = index + page * pageSize + 1;
          return item;
        });
        this.setState({
          expenseTypeIds,
          loading: false,
          data: res.data.rows,
          pagination: {
            total: res.data.total,
            onChange: this.onChangePager,
            current: this.state.page + 1
          }
        })
      }
    }).catch(() => {
      this.setState({ loading: false });
      message.error(messages('common.error1')/*获取数据失败，请稍后重试或联系管理员*/)
    })
  }

  onChangePager = (page) => {
    const { expenseTypeIds } = this.state;
    if(page - 1 !== this.state.page)
      this.setState({ page: page - 1, }, () => this.getList({ expenseTypeIds }))
  };

  handleMenuClick = (e) => {
    switch (e.key) {
      case 'invoice':
        this.setState({ receiptOperateScene: 1 });
        break;
      case 'businessCard':
        break;
      default:
        this.setState({ receiptOperateScene: 2 });
    }
    this.setState({showExpenseFlag: true, nowExpense: null, expenseSource: e.key});
  };

  renderExpandedRowCost = (title, content, key) => {
    return (
      <div key={key}>
        <span>{title}</span>
        {content && <span>:{content}</span>}
      </div>
    )
  };

  renderExpandedRow= (type) => {
    return (
      <div className={`${type.level === 'WARN' ? 'warning-expanded-row' : (type.level === 'ERROR' ? 'error-expand-row' : '')}`} >
        <span>{type.name}</span>
        {type.toast && <span>:{type.toast}</span>}
      </div>
    )
  };

  renderExpandedSpan = (type) => {
    return (
      <span>{type.name}/</span>
    )
  };

  renderClass = (record) =>{
    return record.invoiceLabels.length > 0  ?  '' : 'row-expand-display-none';
  };

  renderAllExpandedRow = (record) => {
    let result = [];
    let infoRes = [];
    let types = record.invoiceLabels || [];
    let lastIndex = -1;
    types.map((label, index) => {
      if (label.level !== 'INFO') {
        result.push(this.renderExpandedRow(label, '', index));
      } else {
        lastIndex = label.name;
        infoRes.push(this.renderExpandedSpan(label, '', index));
      }
    });
    let infoLength = infoRes.length;
    infoLength > 0 && (infoRes[infoLength - 1] = <span key="lastIndex">{lastIndex}</span>);
    result.push(infoRes);
    return result.length > 0 ? result :  null;
  };

  handleCloseExpense = (refresh) => {
    const { expenseTypeIds } = this.state;
    this.setState({showExpenseFlag: false}, () => {
      refresh === true && this.getList({ expenseTypeIds });
    })
  };

  //选中项发生变化的时的回调
  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys })
  };

  //修改转交人
  changeTransfer = (value) => {
    let item = value || {};
    this.setState({
      reimbursementUserId: item.id,
      reimbursementUserOID: item.userOID,
      reimbursementUserName: item.fullName
    })
  };

  //转交
  handleToTransfer = () => {
    const { selectedRowKeys, reimbursementUserId, expenseTypeIds } = this.state;
    if (reimbursementUserId) {
      let params = {
        reimbursementUserId,
        invoiceOIDs: selectedRowKeys
      };
      this.setState({ transferLoading: true });
      expenseService.transferExpense(params).then(() => {
        this.setState({
          transferLoading: false,
          modalVisible: false,
          selectedRowKeys: []
        });
        message.success(messages('common.operate.success'));
        this.getList({ expenseTypeIds })
      }).catch(e => {
        errorMessage(e.response);
        this.setState({ transferLoading: false })
      })
    } else {
      this.setState({ transferLoading: false });
      message.error(messages('my-account.key172')/*请选择转交人*/)
    }
  };

  // 清空条件
  handleClearParams = () => {
    this.setState({ page: 0 }, () => this.getList());
  };
// 搜索
  handleSearch = (ids) => {
    this.setState({ page: 0 }, () => this.getList(ids));
  };

  render(){
    const { loading, data, pagination, columns, showExpenseFlag, nowExpense, expenseSource,
      businessCardEnabled, invoiceEnabled, selectedRowKeys, modalVisible, transferLoading, reimbursementUserOID,
      receiptOperateScene, isCopy, reimbursementUserName, debounceSlideFrame, searchForm
    } = this.state;
    const { user, profile } = this.props;
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        <Menu.Item key="expenseType">{messages('my-account.key64'/*手工添加*/)}</Menu.Item>
        { invoiceEnabled && <Menu.Item key="invoice">{messages('my-account.key65'/*发票查验*/)}</Menu.Item> }
        { businessCardEnabled && <Menu.Item key="businessCard">{messages('my-account.key66'/*导入商务卡费用*/)}</Menu.Item> }
      </Menu>
    );
    const rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: this.onSelectChange
    };
    return(
      <div className="my-account">
        <SearchArea
          searchForm={searchForm}
          isReturnLabel={true}
          submitHandle={this.handleSearch}
          clearHandle={this.handleClearParams}/>
        <div className="operate-area">
          <Dropdown overlay={menu}>
            <Button className="new-btn">
              {messages('my-account.key67'/*新建费用*/)} <Icon type="down" />
            </Button>
          </Dropdown>
          {profile['expense.deliver.others'] && (
            <Condition>
              <If value={selectedRowKeys.length}>
                <Button onClick={() => this.setState({reimbursementUserOID: '', modalVisible: true})}>
                  {messages('my-account.key173')/*转交*/}
                </Button>
              </If>
              <Else>
                <Tooltip title={messages('my-account.key174')/*请勾选费用*/}>
                  <Button disabled>{messages('my-account.key173')/*转交*/}</Button>
                </Tooltip>
              </Else>
            </Condition>
          )}
        </div>
        <ResizeTable
          dataSource={data}
          size="middle"
          bordered
          onRow={record => ({
            onClick: () => (
              this.setState({ showExpenseFlag: true, nowExpense: record, isCopy: false, debounceSlideFrame: true }, () => {
                setTimeout(() => {
                  this.setState({ debounceSlideFrame: false })
                }, 600)
              })
            )
          })}
          defaultExpandAllRows={true}
          expandedRowRender={this.renderAllExpandedRow}
          rowKey="invoiceOID"
          rowClassName={this.renderClass}
          loading={loading}
          columns={columns}
          onExpand={this.onExpand}
          rowSelection={profile['expense.deliver.others'] ? rowSelection : null}
          pagination={pagination}
        />
        <SlideFrame
          show={showExpenseFlag}
          title={nowExpense && !isCopy ? messages('my-account.key178')/*编辑费用*/ : messages('my-account.key67'/*新建费用*/)}
          content={NewExpense}
          hasFooter={false}
          params={{
            nowExpense,
            expenseSource,
            slideFrameShowFlag: showExpenseFlag,
            businessCardEnabled,
            user,
            hasInit: false,
            receiptOperateScene,
            isCopy
          }}
          onClose={() => !debounceSlideFrame && this.setState({showExpenseFlag: false, nowExpense: null, expenseSource: ''})}
          afterClose={this.handleCloseExpense}
          width="800px"
        />
        <Modal
          visible={modalVisible}
          title={messages('my-account.key173')/*转交*/}
          footer={(
            <div>
              <Button onClick={() => this.setState({modalVisible: false})}>{messages('common.cancel')}</Button>
              <Button type="primary" loading={transferLoading} onClick={this.handleToTransfer}>{messages('common.ok')}</Button>
            </div>
          )}
          onCancel={() => this.setState({modalVisible: false})}
        >
          <Alert message={messages('my-account.key234',{arg1:reimbursementUserName})/*转交后的费用只能由统一报销人{arg1}报销*/} type="info" showIcon />
          <Row style={{marginTop: 20}}>
            <Col span={6} style={{textAlign: 'right', paddingRight: 10, lineHeight: '32px'}}>{messages('my-account.key176')/*转交给*/}：</Col>
            <Col span={14}>
              <Selector
                type="user"
                entity
                params={{keyword: '', roleType: 'TENANT', setOfBooksId: this.props.company.setOfBooksId, status: 1001}}
                value={reimbursementUserOID}
                placeholder={messages('my-account.key177')/*请按照姓名/工号/手机号搜索*/}
                onChange={this.changeTransfer}
              />
            </Col>
          </Row>
        </Modal>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    profile: state.login.profile
  }
}

export default connect(mapStateToProps)(MyAccount);
